<template>
    <div class="instance-container layout-pd">
        <el-card shadow="hover" style="border: 0;">
            <div class="instance-search mb15">
                <el-input size="default" v-model="state.searchForm.keyword" placeholder="实例名称/描述/创建人" clearable
                    style="max-width: 300px;margin:5px">
                </el-input>
                <el-select v-model="state.searchForm.type" clearable placeholder="实例类型" size="normal"
                    style="width: 200px;margin:5px">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

                <el-button size="default" type="primary" @click="handleSearch" class="ml10">
                    <el-icon>
                        <ele-Search />
                    </el-icon>
                    搜索
                </el-button>
                <el-button size="default" @click="resetSearch" type="default" class="ml10">
                    重置
                </el-button>
            </div>
            <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="instance in paginatedData" :key="instance.id">
                    <el-card :body-style="{ padding: '0px' }" shadow="hover" class="instance-card">
                        <div class="card-image-container">
                            <el-image :src="instance.image" fit="cover" class="instance-image">
                                <template #error>
                                    <div class="image-error">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </div>
                        <div class="card-content">
                            <div class="instance-header">
                                <span class="instance-title" :title="instance.name">{{ instance.name }}</span>
                                <el-tag :type="instance.type === 'scene' ? 'success' : 'primary'" size="small">
                                    {{ instance.typeLabel }}
                                </el-tag>
                            </div>
                            <div class="instance-desc" :title="instance.description">
                                {{ instance.description }}
                            </div>
                            <div class="instance-meta">
                                <span class="meta-item">
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                    {{ instance.creator }}
                                </span>
                                <span class="meta-item">
                                    <el-icon>
                                        <Clock />
                                    </el-icon>
                                    {{ instance.createTime }}
                                </span>
                            </div>
                            <div class="instance-actions">
                                <el-button size="small" type="primary" text @click.stop="handleEdit(instance)">
                                    <el-icon>
                                        <Edit />
                                    </el-icon> 编辑
                                </el-button>
                                <el-button size="small" type="danger" text @click.stop="handleDelete(instance.id)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon> 删除
                                </el-button>
                                <el-button v-if="instance.hasChildren" size="small" type="success" text
                                    @click.stop="handleViewChildren(instance)">
                                    <el-icon>
                                        <FolderOpened />
                                    </el-icon> 子实例
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <div class="pagination-container">
                <el-pagination v-model:current-page="state.pagination.pageNum"
                    v-model:page-size="state.pagination.pageSize" :page-sizes="[12, 24, 36, 48]" :small="false"
                    :background="true" layout="total, sizes, prev, pager, next, jumper" :total="state.pagination.total"
                    @size-change="handleSizeChange" @current-change="handlePageChange" />
            </div>
        </el-card>

        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">

            <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="实例信息" name="first">
                    <el-form :model="currentInstance" label-width="100px">
                        <el-form-item label="实例名称">
                            <el-input v-model="currentInstance.name" placeholder="请输入实例名称" />
                        </el-form-item>
                        <el-form-item label="实例描述">
                            <el-input v-model="currentInstance.description" type="textarea" :rows="3"
                                placeholder="请输入实例描述" />
                        </el-form-item>
                        <el-form-item label="实例类型" v-if="!currentInstance.parentId">
                            <el-radio-group v-model="currentInstance.type">
                                <el-radio-button label="scene">场景仿真模型</el-radio-button>
                                <el-radio-button label="equipment">装备仿真模型</el-radio-button>
                            </el-radio-group>
                        </el-form-item>

                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="实例配置" name="second">
                    <el-form :model="currentInstance" label-width="100px">
                        <el-form-item label="初始速度">
                            <el-input v-model="currentInstance.velocity" placeholder="请输入实例初始速度" />

                        </el-form-item>
                        <el-form-item label="步长">
                            <el-input v-model="currentInstance.step" placeholder="请输入实例步长" />
                        </el-form-item>


                    </el-form>
                </el-tab-pane>

            </el-tabs>



            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveInstance">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import {
    Edit, Delete, Search, User, Clock, FolderOpened, Picture
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'

// 类型定义
interface InstanceItem {
    id: string
    parentId?: string
    name: string
    description: string
    image: string
    type: 'scene' | 'equipment'
    typeLabel: string
    creator: string
    createTime: string
    hasChildren?: boolean
    velocity?: string | number
    step?: string | number
}

// 状态管理
const state = reactive({
    allData: [] as InstanceItem[],
    loading: false,
    pagination: {
        pageNum: 1,
        pageSize: 12,
        total: 0
    },
    searchForm: {
        keyword: '',
        type: ''
    }
})
const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}
// 下拉选项
const typeOptions = [
    { value: 'scene', label: '场景仿真模型' },
    { value: 'equipment', label: '装备仿真模型' }
]

// 模拟数据
const mockImages = [
    'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
    'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
    'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
    'https://fuss10.elemecdn.com/9/bb/e27858e47d3f141b5d02fc0459396jpeg.jpeg',
    'https://fuss10.elemecdn.com/d/e6/c4d9303e02d737b810b470263f56ejpeg.jpeg',
    'https://fuss10.elemecdn.com/3/28/bbf893f792f03a1990ee4f95ba307jpeg.jpeg',
    'https://fuss10.elemecdn.com/2/11/6535bcfb6115322b7412185c25874jpeg.jpeg',
    'https://fuss10.elemecdn.com/1/88/4b57bf3c7f63793719d9983e93216jpeg.jpeg'
]

const mockDescriptions = [
    '城市交通流量仿真模型，用于分析高峰时段道路拥堵情况',
    '军事装备作战效能评估模型，模拟不同武器系统的作战效果',
    '物流配送中心仿真系统，优化货物分拣和运输流程',
    '机场航班起降调度模型，提高航班准点率和跑道利用率',
    '电力系统故障恢复仿真，测试电网在故障后的恢复策略',
    '化工生产过程模拟，优化反应条件和产物收率',
    '医院急诊流程仿真，减少患者等待时间和资源浪费',
    '零售商店客流分析模型，优化商品陈列和人员配置'
]

const mockCreators = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']

// 生成模拟数据
const generateMockData = () => {
    const data: InstanceItem[] = []
    const now = new Date()

    // 生成父实例
    for (let i = 1; i <= 20; i++) {
        const hasChildren = Math.random() > 0.3
        const type = Math.random() > 0.5 ? 'scene' : 'equipment'
        const imageIndex = (i - 1) % mockImages.length

        data.push({
            id: `p${i}`,
            name: `${type === 'scene' ? '场景' : '装备'}仿真模型${i}`,
            description: mockDescriptions[imageIndex],
            image: mockImages[imageIndex],
            type,
            typeLabel: type === 'scene' ? '场景仿真模型' : '装备仿真模型',
            creator: mockCreators[Math.floor(Math.random() * mockCreators.length)],
            createTime: formatDate(new Date(now.getTime() - Math.floor(Math.random() * 30) * 86400000)),
            hasChildren,
            velocity: 10,
            step: 2
        })

        // 生成子实例
        if (hasChildren) {
            const childCount = Math.floor(Math.random() * 3) + 1
            for (let j = 1; j <= childCount; j++) {
                data.push({
                    id: `c${i}-${j}`,
                    parentId: `p${i}`,
                    name: `子模型${i}-${j}`,
                    description: `${mockDescriptions[imageIndex]}的变体${j}`,
                    image: mockImages[(imageIndex + j) % mockImages.length],
                    type,
                    typeLabel: type === 'scene' ? '场景仿真模型' : '装备仿真模型',
                    creator: mockCreators[Math.floor(Math.random() * mockCreators.length)],
                    createTime: formatDate(new Date(now.getTime() - Math.floor(Math.random() * 15) * 86400000)),
                    velocity: 10,
                    step: 2
                })
            }
        }
    }

    return data
}

// 格式化日期
const formatDate = (date: Date) => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 计算属性：过滤后的数据
const filteredData = computed(() => {
    let result = [...state.allData]

    // 关键字搜索
    if (state.searchForm.keyword) {
        const keyword = state.searchForm.keyword.toLowerCase()
        result = result.filter(item =>
            item.name.toLowerCase().includes(keyword) ||
            item.description.toLowerCase().includes(keyword) ||
            item.creator.toLowerCase().includes(keyword)
        )
    }

    // 类型筛选
    if (state.searchForm.type) {
        result = result.filter(item => item.type === state.searchForm.type)
    }

    return result
})

// 计算属性：当前页数据
const paginatedData = computed(() => {
    const start = (state.pagination.pageNum - 1) * state.pagination.pageSize
    const end = start + state.pagination.pageSize
    return filteredData.value.slice(start, end)
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('编辑实例')
const currentInstance = ref<InstanceItem>({
    id: '',
    name: '',
    description: '',
    image: '',
    type: 'scene',
    typeLabel: '',
    creator: '',
    createTime: '',
    velocity: "",
    step: ""
})

// 方法
const fetchData = async () => {
    state.loading = true
    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        state.allData = generateMockData()
        state.pagination.total = state.allData.length
    } finally {
        state.loading = false
    }
}

const handleSearch = () => {
    state.pagination.pageNum = 1
    state.pagination.total = filteredData.value.length
}

const resetSearch = () => {
    state.searchForm = {
        keyword: '',
        type: ''
    }
    handleSearch()
}

const handlePageChange = (page: number) => {
    state.pagination.pageNum = page
}

const handleSizeChange = (size: number) => {
    state.pagination.pageSize = size
    state.pagination.pageNum = 1
}

const handleEdit = (instance: InstanceItem) => {
    currentInstance.value = { ...instance }
    dialogTitle.value = instance.parentId ? '编辑子实例' : '编辑实例'
    dialogVisible.value = true
}

const handleDelete = (id: string) => {
    ElMessageBox.confirm('确定要删除该实例吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        state.allData = state.allData.filter(item => item.id !== id)
        state.pagination.total = filteredData.value.length
        ElMessage.success('删除成功')
    }).catch(() => {
        // 取消删除
    })
}

const handleViewChildren = (parent: InstanceItem) => {
    // 在实际项目中，这里应该跳转到子实例列表页面
    // 这里我们模拟一个提示
    ElMessage.info(`正在查看 "${parent.name}" 的子实例`)
    // 实际实现可能是：
    // router.push({ path: '/instance/children', query: { parentId: parent.id } })
}

const saveInstance = () => {
    const index = state.allData.findIndex(item => item.id === currentInstance.value.id)
    if (index !== -1) {
        // 更新现有实例
        state.allData[index] = { ...state.allData[index], ...currentInstance.value }
    } else {
        // 新增实例（实际项目中应该有单独的新增逻辑）
        const newId = `p${state.allData.length + 1}`
        state.allData.push({
            ...currentInstance.value,
            id: newId,
            createTime: formatDate(new Date()),
            creator: '当前用户',
            velocity: 10,
            step: 2
        })
    }

    dialogVisible.value = false
    state.pagination.total = filteredData.value.length
    ElMessage.success('保存成功')
}

// 生命周期
onMounted(() => {
    fetchData()
})
</script>

<style lang="scss" scoped>
.instance-container {
    .instance-search {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 10px;
        margin-bottom: 20px;
    }

    .instance-card {
        margin-bottom: 20px;
        transition: all 0.3s ease;
        height: 100%;
        display: flex;
        flex-direction: column;

        &:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .card-image-container {
            position: relative;
            width: 100%;
            height: 160px;
            overflow: hidden;

            .instance-image {
                width: 100%;
                height: 100%;
                transition: transform 0.5s ease;

                &:hover {
                    transform: scale(1.05);
                }
            }

            .image-error {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #f5f7fa;
                color: #909399;
                font-size: 24px;
            }
        }

        .card-content {
            padding: 15px;
            flex: 1;
            display: flex;
            flex-direction: column;

            .instance-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8px;

                .instance-title {
                    font-size: 16px;
                    font-weight: 600;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    flex: 1;
                }
            }

            .instance-desc {
                font-size: 13px;
                color: #666;
                margin-bottom: 12px;
                line-height: 1.5;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                flex: 1;
            }

            .instance-meta {
                display: flex;
                align-items: center;
                font-size: 12px;
                color: #909399;
                margin-bottom: 15px;

                .meta-item {
                    display: flex;
                    align-items: center;
                    margin-right: 15px;

                    .el-icon {
                        margin-right: 5px;
                        font-size: 14px;
                    }
                }
            }

            .instance-actions {
                display: flex;
                justify-content: flex-end;
                margin-top: auto;

                .el-button {
                    padding: 0 8px;
                    font-size: 12px;
                }
            }
        }
    }

    .pagination-container {
        margin-top: 30px;
        display: flex;
        justify-content: center;
    }
}
</style>